﻿using System;
using System.Collections.Generic;
using System.Text;
using ZLDC.Common.BaseUser;
using System.Web;
using System.Data;
using System.Text.RegularExpressions;

namespace ZLDC.Common.Estate
{
    public class _Utility
    {
        /// <summary>
        /// 拆分整串为字符串数据
        /// </summary>
        /// <param name="str"> 原串(12,14,13,15....) </param>
        /// <param name="sign"> 拆分字符(',' '|'...) </param>
        /// <returns></returns>
        public static string[] GetStringBySplit(string str, char sign)
        {
            if (str == "")
                return null;

            try
            {
                if (str.Substring(0, 1) == @sign.ToString())  // 去掉最前面的字符
                {
                    str = str.Substring(1, str.Length - 1);
                }
                if (str.Substring(str.Length - 1, 1) == sign.ToString()) // 去掉最后面的字符
                {
                    str = str.Substring(0, str.Length - 1);
                }
            }
            catch { }

            return str.Split(sign);
        }

        /// <summary>
        /// 获取总页数
        /// </summary>
        /// <param name="pagesize"> 每页显示多少 </param>
        /// <param name="total"> 总记录数 </param>
        /// <returns></returns>
        public static int GetPageAll(int pagesize, int total)
        {
            return ((total % pagesize == 0) ? (total / pagesize) : (total / pagesize + 1));
        }

        #region 指定错误页面

        /// <summary>
        /// 跳转到自定义错误页(指定到系统繁忙页)
        /// </summary>
        public static void GoError()
        {
            GoError("系统繁忙，请稍候访问！");
        }

        /// <summary>
        /// 跳转到自定义错误页
        /// </summary>
        /// <param name="errormsg"></param>
        public static void GoError(string errormsg)
        {
            System.Web.HttpContext.Current.Response.Redirect("~/Error.aspx?errormsg=" + System.Web.HttpUtility.UrlEncode(errormsg));
        }

        #endregion

        #region GetChineseSpell获取汉字拼音的第一个字母

        /// <summary>
        /// 获取汉字拼音的第一个字母
        /// </summary>
        /// <param name="strText"> 中文字符串 </param>
        /// <returns></returns>
        public static string GetChineseSpell(string strText)
        {
            if (strText.Equals(""))
                return "";

            int len = strText.Length;
            string myStr = "";
            for (int i = 0; i < len; i++)
            {
                myStr += getSpell(strText.Substring(i, 1));
            }
            return myStr;
        }

        /// <summary>
        /// 获取汉字数组拼音的第一个字母
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
        public static string[] GetChineseSpell(string[] strText)
        {
            int len = strText.Length;
            string[] myStr = null;
            for (int i = 0; i < len; i++)
            {
                myStr[i] = getSpell(strText[i]);
            }
            return myStr;
        }

        /// <summary>
        /// 获取单个中文的首字母
        /// </summary>
        /// <param name="cnChar"></param>
        /// <returns></returns>
        private static string getSpell(string cnChar)
        {
            byte[] arrCN = Encoding.Default.GetBytes(cnChar);
            if (arrCN.Length > 1)
            {
                int area = (short)arrCN[0];
                int pos = (short)arrCN[1];
                int code = (area << 8) + pos;
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };

                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25)
                    {
                        max = areacode[i + 1];
                    }
                    if (areacode[i] <= code && code < max)
                    {
                        return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    }
                }
                return "*";
            }
            else return cnChar;
        }

        #endregion

        #region 登录用户信息

        /// <summary>
        /// 从session中取出当前登录用户信息
        /// </summary>
        /// <returns></returns>
        public static Param GetInfoBySession()
        {
            if (HttpContext.Current.Session["info"] == null)
            {
                HttpContext.Current.Response.Write("<script language=\"javascript\">alert(\"权限失效!请重新登陆！\");parent.parent.location.href=\"http://\"+location.hostname+\":\"+location.port+\"/Login.aspx\"; </script>");
                HttpContext.Current.Response.End();
            }

            Param info = (Param)HttpContext.Current.Session["info"];

            return info;
        }

        /// <summary>
        /// 获取某 分行经理|组别经理 下所有员工ID
        /// </summary>
        /// <param name="userid"> 分行经理ID </param>
        /// <returns> </returns>
        public static string GetUserList(int deptid)
        {
            string userlist = "";

            using (_Database db = new _Database("ZLDCHR"))
            {
                DataSet ds = db.Query(" select * from v_UserInfo where t_id = " + deptid);
                if (ds != null && ds.Tables.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    int length = dt.Rows.Count;

                    for (int i = 0; i < length; i++)
                    {
                        userlist += dt.Rows[i]["userid"].ToString();
                        if (i < length - 1)
                            userlist += ",";
                    }
                }
            }

            return userlist;
        }

        /// <summary>
        /// 分割工号和用户姓名
        /// </summary>
        /// <param name="sNameList"> 如：邵从良[19120,信息技术部] </param>
        /// <param name="userName"> 邵从良 </param>
        /// <param name="userNo"> 19120 </param>
        public static void GetUserNoAndUserName(string sNameList, out string userName, out string userNo)
        {
            userNo = string.Empty;

            if (sNameList.Trim().Contains("["))
                userName = sNameList.Substring(0, sNameList.LastIndexOf("[")).ToString().Trim();
            else
            {
                userName = sNameList.Trim();
                userNo = sNameList.Trim();
                return;
            }

            if (userName != string.Empty)
            {
                sNameList = sNameList.Replace(userName, string.Empty).Replace("[", string.Empty).Replace("]", string.Empty).Trim();
                if (sNameList.Trim().Contains(","))
                    userNo = sNameList.Substring(0, sNameList.LastIndexOf(",")).ToString().Trim();
                else
                    userNo = sNameList.Trim();
            }
        }

        public static void GetUserId(string sNameList, out string userName, out string userNo)
        {
            userNo = string.Empty;

            if (sNameList.Trim().Contains("["))
                userName = sNameList.Substring(0, sNameList.LastIndexOf("[")).ToString().Trim();
            else
            {
                userName = "";
                userNo = sNameList.Trim();
                return;
            }

            if (userName != string.Empty)
            {
                sNameList = sNameList.Replace(userName, string.Empty).Replace("[", string.Empty).Replace("]", string.Empty).Trim();
                if (sNameList.Trim().Contains(","))
                    userNo = sNameList.Substring(0, sNameList.LastIndexOf(",")).ToString().Trim().Replace("L", string.Empty).Replace("G", string.Empty);
                else
                    userNo = sNameList.Trim().Replace("L", string.Empty).Replace("G", string.Empty);
            }
        }


        /// <summary>
        /// 根据各公司ID，查询出公司名称
        /// </summary>        
        /// <returns></returns>
        public static string GetCompanyName()
        {
            int companyId = _Convert.ToInt(_Utility.GetWebConfigSetting("companyId"), 1);   // 公司名称 0集团 1深圳 2广州 3长沙 4武汉 5重庆 6珠海

            string useValue = "";
            if (companyId == 0)
                useValue = "集团";
            else if (companyId == 1)
                useValue = "深圳";
            else if (companyId == 2)
                useValue = "广州";
            else if (companyId == 3)
                useValue = "长沙";
            else if (companyId == 4)
                useValue = "武汉";
            else if (companyId == 5)
                useValue = "重庆";
            else if (companyId == 6)
                useValue = "珠海";

            return useValue;
        }

        /// <summary>
        /// 查询出公司名称串,返回如：('集团','深圳')
        /// </summary>        
        /// <returns></returns>
        public static string GetCompanyNameList()
        {
            int companyId = _Convert.ToInt(_Utility.GetWebConfigSetting("companyId"), 1);   // 公司名称 0集团 1深圳 2广州 3长沙 4武汉 5重庆 6珠海 

            string useValue = "";
            if (companyId == 0)
                useValue = "('集团')";
            else if (companyId == 1)
                useValue = "('集团','深圳')";
            else if (companyId == 2)
                useValue = "('集团','广州')";
            else if (companyId == 3)
                useValue = "('集团','长沙')";
            else if (companyId == 4)
                useValue = "('集团','武汉')";
            else if (companyId == 5)
                useValue = "('集团','重庆')";
            else if (companyId == 6)
                useValue = "('集团','珠海')";

            return useValue;
        }
        /// <summary>
        /// 获取认证地址
        /// </summary>
        /// <returns></returns>
        public static string GetAuthUrl()
        {
            return _Utility.GetWebConfigSetting("AuthUrlSignOut").ToString();
        }

        #endregion

        /// <summary>
        /// 获取webconfig中的值
        /// </summary>
        /// <param name="key"> 键名 </param>
        /// <returns></returns>
        public static string GetWebConfigSetting(string key)
        {
            string value = "";
            try
            {
                value = System.Configuration.ConfigurationManager.AppSettings[key].ToString();
            }
            catch { }

            return value;
        }

        /// <summary>
        /// datarow[] 转换为 datatable
        /// </summary>
        /// <param name="drow1"></param>
        /// <returns></returns>
        public static DataTable GetTable(DataRow[] dr)
        {
            DataTable ndt = new DataTable();
            ndt = dr[0].Table.Clone();              //克隆表结构

            for (int i = 0; i <= dr.Length - 1; i++)
            {
                ndt.ImportRow((DataRow)dr[i]);
            }
            return ndt;
        }

        //字符转数字
        public static int Asc(string character)
        {
            if (character.Length == 1)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
                return (intAsciiCode);
            }
            else
            {
                throw new Exception("Character is not valid.");
            }

        }

        //ASCII码转字符：

        public static string Chr(int asciiCode)
        {
            if (asciiCode >= 0 && asciiCode <= 255)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] byteArray = new byte[] { (byte)asciiCode };
                string strCharacter = asciiEncoding.GetString(byteArray);
                return (strCharacter);
            }
            else
            {
                throw new Exception("ASCII Code is not valid.");
            }
        }

        /// <summary>
        /// 判断字符是否是字母
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool isExists(string str)
        {
            return Regex.Matches(str, "[a-zA-Z]").Count > 0;
        }

    }
}
